<?php

namespace App\Http\Controllers\Api\Website;


use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Requests\LoginRequest;
use App\model\VerifyCode;
use App\User;
use Illuminate\Http\Request;
use Carbon\Carbon;

class AuthController extends Controller
{
    public function login(LoginRequest $request)
    {
        //查询
        $mobile = $request->mobile;
        $code = $request->code;
        $type = $request->type;
        $user = User::where('mobile', $mobile)->first();
        $verifyCode = VerifyCode::where('account', $mobile)->first();
        if ($verifyCode) {
            $time = $verifyCode->updated_at ?? $verifyCode->created_at;
             if(strtotime(now())-strtotime($time)>600){
                 throw new ApiException('验证码已过期');
             }
            if ($code != $verifyCode->verify_code_num) {
                throw  new ApiException('验证码不正确');
            }
        }
        if (!$user) {//注册
            $user = new User();
            $user->mobile = $mobile;
            $user->password = bcrypt('123456');
            $user->name = Carbon::now()->timestamp;
            $user->type = $type;
            $user->save();
        }
        $credentials = ['mobile' => $mobile, 'password' => '123456'];

        if (!$token = auth('api')->attempt($credentials)) {
             throw new ApiException('登录失败');
        }

        return $this->respondWithToken($token);

    }

   public function logout(){
        auth('api')->logout();
        return response()->json(
            [
                'code'=>0,
                'data'=>'退出成功',
            ]
        );
   }
   public function refresh(){
       return $this->respondWithToken(auth('api')->refresh());
   }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'code' => 0,
            'data' => [
                'access_token' => $token,
                'token_type' => 'bearer',
                'expires_in' => auth('api')->factory()->getTTL() * 60
            ]
        ]);
    }

}
